<?php
namespace App\Services;

use App\Models\College;
use App\Models\YikaoSchoolMajor;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Monolog\Logger;

class SchoolMajorSpiderService
{
    private Client $httpClient;
    private Logger $logger;
    private string $baseUrl = 'https://static-data.gaokao.cn/www/2.0/school/%s/pc_special.json?a=www.gaokao.cn';

    public function __construct(Client $httpClient, Logger $logger)
    {
        $this->httpClient = $httpClient;
        $this->logger = $logger;
    }

    /**
     * 获取所有待采集的院校
     * @param array|null $columns
     * @return array
     */
    public function getAllColleges(?array $columns = null): array
    {
        $query = College::query();

        if ($columns !== null) {
            $query->select($columns);
        }

        return $query->get()->toArray();
    }

    public function crawlSchoolMajorDetail(array $college)
    {
        try {
            $specialId = $college['school_id'] ?? null;
            if (empty($specialId)) {
                throw new \InvalidArgumentException('Missing school_id');
            }

            $url = sprintf($this->baseUrl, $specialId);
            $response = $this->httpClient->get($url);
            $data = json_decode((string)$response->getBody(), true);

            if (empty($data['data'])) {
                throw new \RuntimeException('Empty response data');
            }

            $majors = $data['data']['special_detail']['1'];

            $this->handleFormData($college['school_id'], $majors);

            $this->logger->info("Successfully crawled special detail", [
                'school_id' => $college['school_id'],
                'name' => $major['special_name'] ?? ''
            ]);

            return true;
        } catch (GuzzleException $e) {
            $this->logger->error("HTTP request failed", [
                'error' => $e->getMessage(),
                'special_id' => $major['special_id'] ?? null
            ]);
        } catch (\Exception $e) {
            $this->logger->error("Crawl special detail failed", [
                'error' => $e->getMessage(),
                'special_id' => $major['special_id'] ?? null
            ]);
        }

        return false;
    }

    private function handleFormData($schoolId, $majors): void
    {
        foreach ($majors as $major) {
            YikaoSchoolMajor::query()->updateOrCreate(
                [
                    'school_id' => $schoolId,
                    'special_id' => $major['special_id']
                ],
                [
                    'code' => $major['code'],
                    'is_important' => $major['is_important'],
                    'is_video' => $major['is_video'],
                    'level2_code' => $major['level2_code'],
                    'level2_id' => $major['level2_id'],
                    'level2_name' => $major['level2_name'],
                    'level3_code' => $major['level3_code'],
                    'level3_name' => $major['level3_name'],
                    'level3_weight' => $major['level3_weight'],
                    'limit_year' => $major['limit_year'],
                    'nation_feature' => $major['nation_feature'],
                    'nation_first_class' => $major['nation_first_class'],
                    'province_feature' => $major['province_feature'],
                    'ruanke_level' => $major['ruanke_level'],
                    'ruanke_rank' => $major['ruanke_rank'],
                    'special_name' => $major['special_name'],
                    'special_type' => $major['special_type'],
                    'type_name' => $major['type_name'],
                    'xueke_rank' => $major['xueke_rank'],
                    'xueke_rank_score' => $major['xueke_rank_score'],
                    'year' => $major['year']
                ]
            );
        }
    }
}
